<template>
    <div>
        <report-card :open-dialog="dialog" v-on:closeDialog="dialog = false" :info="video" :type="3"></report-card>
        <v-container fluid>
            <v-row>
                <v-alert prominent class="mx-auto" type="error" v-if="errored">
                    <v-row align="center">
                        <v-col class="grow">
                            <div class="title">Error!</div>
                            <div>
                                出错了！
                            </div>
                        </v-col>
                        <v-col class="shrink">
                            <v-btn @click="actions">重试</v-btn>
                        </v-col>
                    </v-row>
                </v-alert>
                <v-col v-else cols="11" class="mx-auto">
                    <v-icon :small="true">mdi-account</v-icon> {{ onlineCount }}
                    <v-row>
                        <v-col cols="12" sm="12" md="8" lg="8">
                            <div>
                                <v-responsive height="450">
                                    <video ref="videoPlayer" id="my-live" class="video-js vjs-default-skin" controls
                                        preload="auto" style="width: 100%; height: 100%;">
                                        <source :src="video.url" type="application/x-mpegURL" />
                                    </video>
                                </v-responsive>
                                <v-row class="justify-space-between">
                                    <v-col cols="12" sm="6" md="5" lg="5">
                                        <v-card class="transparent" flat>
                                            <v-list-item three-line>
                                                <v-list-item-avatar v-if="typeof video.userId !== 'undefined'"
                                                    size="50">
                                                    <img v-if="video.avatar !== 'no-photo.jpg'" :src="video.avatar
                                                        " :alt="`${video.nickName} avatar`" />
                                                    <v-avatar v-else color="red">
                                                        <span class="white--text headline ">
                                                            {{
                                                                video.nickName
                                                                    .split('')[0]
                                                                    .toUpperCase()
                                                            }}</span>
                                                    </v-avatar>
                                                </v-list-item-avatar>
                                                <v-list-item-content v-if="video.userId" class="align-self-auto">
                                                    <v-list-item-title class="font-weight-medium mb-1">{{
                                                        video.preview }}</v-list-item-title>
                                                    <v-list-item-subtitle>{{ video.fansCount }} 粉丝
                                                    </v-list-item-subtitle>
                                                </v-list-item-content>
                                            </v-list-item>
                                        </v-card>
                                    </v-col>
                                    <v-col cols="12" sm="6" md="4" lg="4">
                                        <div class="d-flex justify-end align-center"
                                            v-if="typeof video.userId !== 'undefined'">
                                            <v-btn v-if="
                                                currentUser && video.userId !== currentUser.userId
                                            " :class="[
                                                { 'red white--text': !subscribed },
                                                {
                                                    'grey grey--text lighten-3 text--darken-3': subscribed
                                                },
                                                'mt-6'
                                            ]" tile large depressed :loading="subscribeLoading" @click="subscribe">{{
                                                !subscribed ?
                                                    '关注' : '已关注' }}</v-btn>

                                            <v-btn v-else-if="showSubBtn" :class="[
                                                { 'red white--text': !subscribed },
                                                {
                                                    'grey grey--text lighten-3 text--darken-3': subscribed
                                                },
                                                'mt-6'
                                            ]" tile large depressed :loading="subscribeLoading" @click="subscribe">{{
                                                !subscribed ?
                                                    '关注' : '已关注' }}</v-btn>
                                            <v-menu bottom left
                                                v-if="currentUser && video.userId !== currentUser.userId">
                                                <template v-slot:activator="{ on }">
                                                    <v-btn icon v-on="on">
                                                        <v-icon>mdi-dots-vertical</v-icon>
                                                    </v-btn>
                                                </template>

                                                <v-list v-if="isAuthenticated">
                                                    <v-list-item @click="report()">
                                                        <v-list-item-title>
                                                            <v-icon>mdi-trash</v-icon>举报
                                                        </v-list-item-title>
                                                    </v-list-item>
                                                </v-list>
                                            </v-menu>
                                            <!-- <v-btn
                            v-if="
                              video.userId && video.userId._id !== currentUser._id
                            "
                            :class="[
                              { 'red white--text': !subscribed },
                              {
                                'grey grey--text lighten-3 text--darken-3': subscribed
                              },
                              'mt-6'
                            ]"
                            tile
                            large
                            depressed
                            :loading="subscribeLoading"
                            @click="subscribe"
                            >{{ !subscribed ? 'subscribe' : 'subscribed' }}</v-btn
                          > -->
                                            <!-- <v-btn icon class="ml-5 mt-6"
                            ><v-icon>mdi-bell</v-icon></v-btn
                          > -->
                                        </div>
                                        <div class="d-flex justify-end align-center"
                                            v-if="typeof video.userId !== 'undefined'">
                                            <v-btn v-if="
                                                currentUser && video.userId === currentUser.userId
                                            " :class="'grey grey--text lighten-3 text--darken-3 mt-6'


                                                " tile large depressed @click="closeLiving">关闭直播</v-btn>

                                            <!-- <v-btn
                            v-if="
                              video.userId && video.userId._id !== currentUser._id
                            "
                            :class="[
                              { 'red white--text': !subscribed },
                              {
                                'grey grey--text lighten-3 text--darken-3': subscribed
                              },
                              'mt-6'
                            ]"
                            tile
                            large
                            depressed
                            :loading="subscribeLoading"
                            @click="subscribe"
                            >{{ !subscribed ? 'subscribe' : 'subscribed' }}</v-btn
                          > -->
                                            <!-- <v-btn icon class="ml-5 mt-6"
                            ><v-icon>mdi-bell</v-icon></v-btn
                          > -->
                                        </div>
                                    </v-col>
                                </v-row>
                                <v-row>
                                    <div class="icon-gallery">
                                        <div v-for="(gift, index) in gifts " :key="index" class="icon-item"
                                            @click="openGiftDialog(gift)">
                                            <img :src="gift.giftImg" style="width: 100px;height: 100px;;" alt="Ticket">
                                            <div>{{ gift.giftName }}</div>
                                            <div class="price">{{ gift.giftValue }}</div>
                                        </div>
                                    </div>
                                </v-row>
                            </div>
                        </v-col>

                        <v-col cols="12" sm="12" md="4" lg="4">
                            <hr class="grey--text" />
                            <h4 class="mb-3 mt-3">弹幕</h4>
                            <div style="height: 450px; overflow-y: scroll;">
                                <div v-for="(gift, i) in receivedGifts" :key="i" class="mb-5">
                                    <v-card v-if="gift.isGift" class="card" tile flat>
                                        {{ gift.nickName }} 送出礼物 <img :src="gift.giftImg"
                                            style="width: 50px;height: 50px;"> X {{ gift.giftCount
                                        }}
                                    </v-card>
                                </div>
                                <div v-for="(message, i) in messageList" :key="i" class="mb-5">
                                    <v-card v-if="!message.isGift" class="card" tile flat>
                                        <v-chip style="background-color: whitesmoke;">
                                            <span style="color: #1B6EF3;">{{ message.nickName }}</span> : <span>{{
                                                message.content }}</span>
                                        </v-chip>
                                    </v-card>
                                </div>
                            </div>
                            <v-row class="justify-space-between">
                                <v-text-field v-model="message" label="消息" class="mb-3" outlined dense></v-text-field>
                                <v-btn class="primary" @click="sendBulletScreen" style="margin-left: 10px;"
                                    depressed>发送</v-btn>
                            </v-row>
                        </v-col>
                    </v-row>
                </v-col>
            </v-row>
            <v-dialog max-width="600" v-model="giftDialog">
                <template v-slot>
                    <v-card title="Dialog" style="text-align: center;">
                        <span class="headline"> 赠送 <span style="color: brown;"> {{ selectedGift.giftName }} </span> 给
                            <span style="color: skyblue;">{{ currentUser.nickName }}</span> </span>
                        <div style="text-align: center;">
                            <img :src="selectedGift.giftImg" style="width: 80px;height: 80px;">
                        </div>
                        <v-row style="max-width: 600px; padding-left: 25%;">
                            <v-btn @click="sub">-</v-btn>
                            <v-text-field v-model="giftCount" label="礼物数量" outlined dense
                                style="max-width:100px; margin:0 10%;"></v-text-field>
                            <v-btn @click="plus">+</v-btn>
                        </v-row>
                        <v-btn @click="sendGift">赠送</v-btn>
                    </v-card>
                </template>
            </v-dialog>
        </v-container>
        <signin-modal :openModal="signinDialog" :details="details" @closeModal="signinDialog = false" />
    </div>
</template>

<script>
import moment from 'moment'
import { mapGetters } from 'vuex'
import { checkFollowing, following } from '@/services/UserRequest'
import { list } from '@/services/VideoRequest'
import { getLiveRoomById } from '@/services/LiveRequest'
// import SubscriptionService from '@/services/SubscriptionService'
// import FeelingService from '@/services/FeelingService'
//import HistoryService from '@/services/HistoryService'
import videojs from "video.js";
import "videojs-contrib-hls";
import SigninModal from '@/components/SigninModal'
import { closeLiving, getLiveUserCount } from '../../services/LiveRequest'
import { giftList } from '../../services/GiftRequest'
import ReportCard from '@/components/ReportCard'

export default {
    data: () => ({
        dialog:false,
        receivedGifts: [],
        giftCount: 1,
        selectedGift: '',
        giftDialog: false,
        gifts: [],
        player: null,
        onlineCount: 0,
        socket: null,
        messageList: [],
        message: '',
        loading: false,
        loaded: false,
        errored: false,
        videoLoading: true,
        subscribed: false,
        subscribeLoading: false,
        showSubBtn: true,
        feeling: '',
        video: {},
        videoId: '',
        videos: [],
        page: 1,
        infiniteId: +new Date(),
        truncate: true,
        signinDialog: false,
        details: {}
    }),
    watch:{
        receivedGifts(){
            setTimeout(()=>{
                this.receivedGifts.unshift()
            },3000)
        }
    },
    computed: {
        ...mapGetters(['currentUser', 'isAuthenticated'])
    },
    methods: {
        report(){
            this.dialog = true
        },
        sub() {
            if (this.giftCount)
                this.giftCount--
        },
        plus() {
            this.giftCount++
        },
        openGiftDialog(gift) {
            this.selectedGift = gift
            this.giftDialog = true
        },
        sendGift() {
            const giftObj = {
                isGift: true,
                userId: this.currentUser.userId,
                nickName: this.currentUser.nickName,
                giftImg: this.selectedGift.giftImg,
                giftValue: this.selectedGift.giftValue,
                giftCount: this.giftCount
            }
            this.socket.send(JSON.stringify(giftObj))
            console.log(giftObj)
            this.giftDialog = false
        },
        getGiftList() {
            giftList()
                .then((res) => {
                    if (res.data.code == 200) {
                        this.gifts = res.data.data
                        console.log(this.gifts)
                    }
                })
        },
        closeLiving() {
            closeLiving(this.video.roomId)
                .then(res => {
                    if (res.data.code == 200) {
                        this.$router.push('/live')
                    }
                })
        },
        sendBulletScreen() {
            const info = {
                isGift: false,
                userId: this.currentUser.userId,
                content: this.message,
                nickName: this.currentUser.nickName
            }
            this.socket.send(JSON.stringify(info))
            this.message = ''
        },
        computeOnlinePeople() {
            getLiveUserCount(this.$route.params.id)
                .then((res) => {
                    this.onlineCount = res.data.data
                })
        },
        initLive(src) {
            this.player = videojs(
                "my-live",
                {
                    bigPlayButton: true,
                    textTrackDisplay: false,
                    posterImage: true,
                    errorDisplay: false,
                    controlBar: true,
                    autoplay: true,
                    muted: true
                }
            );
            this.player.src(src)
        },
        async getLiveRoom(id) {
            this.errored = false
            this.videoLoading = true
            this.video = {}
            try {
                const video = await getLiveRoomById(id)
                if (!video) return this.$router.push('/')
                this.video = video.data.data
                console.log(this.video.url)
                this.checkSubscription(this.video.userId)
                this.initLive(video.data.data.url)
            } catch (err) {
                this.errored = true
                console.log(err)
            } finally {
                this.videoLoading = false
            }
            if (this.currentUser && this.currentUser.userId === this.video.userId) {
                this.showSubBtn = false
            } else {
                this.showSubBtn = true
            }
        },
        async getVideos($state) {
            this.errored = false
            if (!this.loaded) {
                this.loading = true
            }
            const videos = await list({ pageIndex: this.page, pageSize: 5 })
                .catch((err) => {
                    console.log(err)
                    this.errored = true
                })
                .finally(() => (this.loading = false))

            if (typeof videos === 'undefined') return

            if (videos.data.data.length) {
                this.page += 1

                this.videos.push(...videos.data.data)
                if ($state) {
                    $state.loaded()
                }
                this.loaded = true
            } else {
                if ($state) {
                    $state.complete()
                }
            }
        },
        async checkSubscription(id) {
            if (!this.isAuthenticated) return

            this.loading = true
            const sub = await checkFollowing(id)
                .catch((err) => {
                    console.log(err)
                })
                .finally(() => {
                    this.loading = false
                })

            console.log(sub.data.data)
            if (!sub) return

            if (!sub.data.data) this.subscribed = false
            else this.subscribed = true
        },
        async subscribe() {
            if (!this.isAuthenticated) {
                this.signinDialog = true
                this.details = {
                    title: '想要更多关于该博主的视频？',
                    text: '登录即可关注该博主'
                }
                return
            }
            this.subscribeLoading = true
            const sub = await following(this.video.userId)
                .catch((err) => console.log(err))
                .finally(() => {
                    this.subscribeLoading = false
                })

            if (!sub) return
            this.subscribed = !this.subscribed
            if (this.subscribed) {
                this.video.fansCount++
            } else {
                this.video.fansCount--
            }
            // if (!sub.data.data._id) {
            //   this.subscribed = false
            //   this.video.userId.subscribers--
            // } else {
            //   this.subscribed = true
            //   this.video.userId.subscribers++
            // }
        },
        play(e) {
            console.log(e)
        },
        actions() {
            window.location.reload()
        },
        dateFormatter(date) {
            return moment(date).locale('zh-cn').fromNow()
        },
        sendMessage() {
            if (this.socket.readyState === WebSocket.OPEN) {
                const info = {
                    userId: this.channel.userId,
                    message: this.message
                }
                this.socket.send(JSON.stringify(info));
                this.messageList.push(info)
                this.message = ''
                console.log('消息已发送:', this.message)
            } else {
                console.log('WebSocket连接未打开，无法发送消息')
            }
        }
    },
    components: {
        SigninModal,
        ReportCard
    },
    destroyed() {
        console.log('组件已销毁')
        this.socket.close()
        this.player.dispose()
    },
    mounted() {
        this.getLiveRoom(this.$route.params.id)
        this.getGiftList()
        this.socket = new WebSocket('ws://127.0.0.1:8080/live/' + this.$route.params.id, [localStorage.getItem("Authorization")]);
        this.socket.onopen = () => {
            console.log('WebSocket连接已打开');
            // const cache = {
            //     userId: this.$route.params.id,
            //     message: ''
            // }
            // console.log(cache)
            // console.log(JSON.stringify(cache))
            // this.socket.send(JSON.stringify(cache))
        };
        this.socket.onmessage = (event) => {
            if (event.data.charAt(0) == "{") {
                let cacheMessage = JSON.parse(event.data)
                console.log(cacheMessage)
                if (cacheMessage && cacheMessage.content != '' && !cacheMessage.isGift) {
                    this.messageList.push(cacheMessage)
                }
                if (cacheMessage.isGift) {
                    this.receivedGifts.push(cacheMessage)
                }
            } else {
                this.onlineCount = event.data
            }
        };
        this.socket.onclose = (event) => {
            console.log(event)
            console.log('WebSocket连接已关闭');
        };
        // setInterval(()=>{
        //     if(this.receivedGifts.length>=0){
        //         this.receivedGifts.shift()
        //     }
        // },5000)
    },
    beforeRouteUpdate(to, from, next) {
        console.log(from)
        this.page = 1
            ; (this.loading = false), (this.loaded = false), (this.videos = [])
        this.infiniteId += 1
        this.getVideo(to.params.id)
        next()
    },
}
</script>

<style lang="scss">
.grey-color {
    color: #7f7f7f !important;
}

#btns {
    border-bottom: 1px solid #e0d8d8;
}

button.v-btn.remove-hover-bg {
    background-color: initial !important;

    &:hover {
        background-color: #f9f9f9;
    }
}

.icon-gallery {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}

.icon-item {
    text-align: center;
    margin: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    /* 添加背景阴影 */
    transition: transform 0.3s ease;
    /* 添加过渡效果 */
    width: 100px;
    height: 100px;
}

.icon-item:hover {
    cursor: pointer;
    transform: translateY(-5px);
    /* 鼠标悬浮时向上浮动5px */
}

.icon-item img {
    width: 100px;
}

.calculator {
    display: flex;
    justify-content: center;
    align-items: center;
}

button {
    width: 50px;
    height: 50px;
    font-size: 24px;
}

input[type="number"] {
    width: 100px;
    height: 50px;
    text-align: center;
    font-size: 24px;
}

.price {
    color: gray;
}
</style>